package com.ssyt.blog.core.sys.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.ssyt.blog.core.common.BaseDao;
import com.ssyt.blog.core.common.PageModel;
import com.ssyt.blog.core.sys.entity.Blog;

@Repository
public class BlogDao extends BaseDao<Blog, Integer> {

	public Blog getBlog(int userId) {
		return load(userId);
	}

	public PageModel<Object[]> getBlogList(Integer pageNo) {

		return pageMultiPropertyByHql(
				pageNo,
				8,
				"SELECT b.id,b.name,b.description,date_format(b.createTime,'%Y-%m-%d'),u.name FROM Blog b,User u WHERE b.userId=u.id");
	}

	public PageModel<Object[]> getCategoryList(Integer userId, Integer pageNo) {
		List<Object> paramList = new ArrayList<>();
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT c.id,c.name,u.name FROM Category c,User u WHERE c.userId=u.id ");
		if (userId != null) {
			sb.append("AND c.userId=?");
			paramList.add(userId);
		}
		return pageMultiPropertyByHql(pageNo, 8, sb.toString(), paramList);
	}

	public PageModel<Object[]> getArticleList(Integer userId, Integer pageNo) {
		List<Object> paramList = new ArrayList<>();
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT a.id,a.title,a.content,date_format(a.createTime,'%Y-%m-%d'),a.readTimes,c.name,u.name FROM Article a,Category c,User u WHERE a.userId=u.id AND c.id=a.categoryId ");
		if (userId != null) {
			sb.append("AND a.userId=?");
			paramList.add(userId);
		}
		return pageMultiPropertyByHql(pageNo, 8, sb.toString(), paramList);
	}

	public PageModel<Object[]> getDiscussList(Integer userId, Integer pageNo) {
		List<Object> paramList = new ArrayList<>();
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT d.id,d.content,date_format(d.createTime,'%Y-%m-%d'),a.title,u.name FROM Article a,User u,Discuss d WHERE d.userId=u.id AND a.id=d.articleId ");
		if (userId != null) {
			sb.append("AND a.userId=?");
			paramList.add(userId);
		}
		return pageMultiPropertyByHql(pageNo, 8, sb.toString(), paramList);
	}

	public void blogInfoDelete(Integer id) {
		Blog blog = load(id);
		delete(blog);
	}

}
